/*
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: ShareProfitActivity.java
 *   @Date: 19-5-29 下午5:05
 *   @Author: ppzhao
 *   @Description:
 *   @Copyright（C）: 2019 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 */

package io.bhex.app.share.ui;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import io.bhex.app.BuildConfig;
import io.bhex.app.R;
import io.bhex.app.ScreenShot.BitmapUtils;
import io.bhex.app.base.BaseActivity;
import io.bhex.app.qrcode.zxing.QRCodeEncoder;
import io.bhex.app.share.SHARE_MEDIA;
import io.bhex.app.share.ShareUtils;
import io.bhex.app.share.SystemShareUtils;
import io.bhex.app.share.adapter.ShareVPAdater;
import io.bhex.app.share.presenter.ContractShareProfitPresenter;
import io.bhex.app.utils.CommonUtil;
import io.bhex.app.utils.DialogUtils;
import io.bhex.app.utils.KlineUtils;
import io.bhex.app.utils.NumberUtils;
import io.bhex.app.utils.ShareConfigUtils;
import io.bhex.app.utils.SkinColorUtil;
import io.bhex.app.view.ScalePageTransformer;
import io.bhex.baselib.images.CImageLoader;
import io.bhex.baselib.utils.DebugLog;
import io.bhex.baselib.utils.ImageUtils;
import io.bhex.baselib.utils.PixelUtils;
import io.bhex.baselib.utils.ToastUtils;
import io.bhex.baselib.utils.ViewFinder;
import io.bhex.sdk.config.bean.ShareConfigBean;
import io.bhex.sdk.data_manager.RateAndLocalManager;
import io.bhex.sdk.invite.bean.InviteResponse;
import io.bhex.sdk.trade.futures.bean.FuturesPositionOrder;
import pub.devrel.easypermissions.EasyPermissions;

public class ContractShareProfitActivity extends BaseActivity<ContractShareProfitPresenter, ContractShareProfitPresenter.ContractShareProfitUI> implements ContractShareProfitPresenter.ContractShareProfitUI, EasyPermissions.PermissionCallbacks, View.OnClickListener {
    private static final int WRITE_EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE = 2;
    private static final String COPYWRITING_KEY_PROFIT = "profit_";
    private static final String COPYWRITING_KEY_LOSS = "loss_";
    private static final String COPYWRITING_KEY_JUST = "just_";
    private View shareView;
    //    private String resultPath;
    private String shareUrl;
    private ShareConfigBean currentShareConfig;
    private ViewPager viewPager;
    private ShareVPAdater shareProfitVPAdater;
    private List<View> shareViews = new ArrayList<>();

    /**
     * 3种状态，1盈利，2亏损，3不盈利（+0.00%）
     *
     * 盈利随机文案：
     * 挣这点不够，我还要更多
     * I'm Rich
     * 多买多涨，人生赢家
     * 哈哈，离100倍不远了
     *
     * 亏损随机文案：
     * 被割了，呜呜
     * 人在币市飘，哪有不挨刀
     * 我还会挣回来的
     * 啊啊，我的别墅没了
     *
     *
     *
     * 不盈利0随机文案：
     * 不挣不亏，刚刚好
     * 没亏就是挣！
     *
     * 1.期权分享需要包含内容
     * 多空，期权名称，持仓均价，当前价格
     *
     * 2.合约分享
     * 多空，杠杆倍数，合约名称，持仓均价，当前价格
     *
     *
     * . Profit
     * Never satisfied with these profit
     * I AM RICH
     * Greedyisgood
     * todaMOOOOOOON
     *
     * 2. LOSS
     * Cry for my $
     * In Crypto we HOLD
     * I WILL BE BACK
     * Where is the bull
     *
     * 3. +0.00%
     * Breakeven is a bless
     * No loss = big gain
     */

    private String[] profitCopyWritingsZh = new String[]{
            "挣这点不够，我还要更多",
            "多买多涨，人生赢家",
            "哈哈，离100倍不远了"
    };

    private String[] profitCopyWritingsEn = new String[]{
            "Never satisfied with these profit",
            "I AM RICH",
            "Greedyisgood",
            "todaMOOOOOOON"
    };

    private String[] lossCopyWritingsZh = new String[]{
            "被割了，呜呜",
            "人在币市飘，哪有不挨刀",
            "我还会挣回来的",
            "啊啊，我的别墅没了"
    };

    private String[] lossCopyWritingsEn = new String[]{
            "Cry for my $",
            "In Crypto we HOLD",
            "I WILL BE BACK",
            "Where is the bull"
    };

    private String[] justCopyWritingsZh = new String[]{
            "不挣不亏，刚刚好",
            "没亏就是挣！"
    };

    private String[] justCopyWritingsEn = new String[]{
            "Breakeven is a bless",
            "No loss = big gain"
    };

    private HashMap<String,String[]> copyWritingsMap = new HashMap<>();

    @Override
    protected int getContentView() {
        return R.layout.activity_share_profit_layout;
    }

    @Override
    protected ContractShareProfitPresenter createPresenter() {
        return new ContractShareProfitPresenter();
    }

    @Override
    protected ContractShareProfitPresenter.ContractShareProfitUI getUI() {
        return this;
    }

    @Override
    protected void initView() {
        super.initView();
        loadCopyWritings();

        Intent intent =getIntent();
        FuturesPositionOrder holdOrderBean = (FuturesPositionOrder)intent.getSerializableExtra("hold");

        //分享view初始化
        viewPager = viewFinder.find(R.id.viewPager);
        viewFinder.find(R.id.rootView).setBackgroundColor(getResources().getColor(CommonUtil.isBlackMode()? R.color.dark80 : R.color.dark80));

        loadShareProfitViews(holdOrderBean);

        String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE};
        if (!EasyPermissions.hasPermissions(this, perms)) {
            EasyPermissions.requestPermissions(this, getString(R.string.file_read_write_permission_hint), WRITE_EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE, perms);
        }

        setShareList();

    }

    /**
     * 设置支持的分享列表
     */
    private void setShareList() {
        if (TextUtils.isEmpty(BuildConfig.WEIXIN_ID)) {
            viewFinder.find(R.id.shareWx).setVisibility(View.GONE);
            viewFinder.find(R.id.shareWxFriends).setVisibility(View.GONE);
            viewFinder.textView(R.id.moreBtnTitle).setText(getString(R.string.string_share));
        }else{
            viewFinder.textView(R.id.moreBtnTitle).setText(getString(R.string.string_more));
        }
    }

    private String getCopyWritings(String changed) {
        String localCode = RateAndLocalManager.GetInstance(this).getCurLocalKind().code;
        if (localCode.equalsIgnoreCase(RateAndLocalManager.LocalKind.zh.code)) {

        }

        String keyPrefix = "";
        if (!TextUtils.isEmpty(changed)) {
            double diff = NumberUtils.sub(changed, "0");
            if (diff>0) {
                keyPrefix = COPYWRITING_KEY_PROFIT;
            }else if(diff==0){
                keyPrefix = COPYWRITING_KEY_JUST;
            }else{
                keyPrefix = COPYWRITING_KEY_LOSS;
            }

        }else{
            keyPrefix = COPYWRITING_KEY_JUST;
        }

        String[] copyWritings;
        String key = keyPrefix+localCode;
        if (copyWritingsMap.containsKey(key)) {
            copyWritings = copyWritingsMap.get(key);
        }else{
            copyWritings = copyWritingsMap.get(keyPrefix + RateAndLocalManager.LocalKind.en.code);
        }
        if (copyWritings != null && copyWritings.length>0) {
            DebugLog.e("XXXX","random arry = "+copyWritings.toString() +"  "+copyWritings.length);
            int length = copyWritings.length;
            int max = length -1;
            int min = 0;
            int indexOfRandom = (int)(Math.random()*(max-min+1)) +min;
            DebugLog.e("XXXX","random = "+indexOfRandom);
            String result = copyWritings[indexOfRandom];
            DebugLog.e("XXXX","random Str = "+result);
            return result;
        }else{
            return "";
        }

    }

    private void loadCopyWritings() {
        copyWritingsMap.put(COPYWRITING_KEY_PROFIT + RateAndLocalManager.LocalKind.zh.code,profitCopyWritingsZh);
        copyWritingsMap.put(COPYWRITING_KEY_PROFIT + RateAndLocalManager.LocalKind.en.code,profitCopyWritingsEn);
        copyWritingsMap.put(COPYWRITING_KEY_LOSS + RateAndLocalManager.LocalKind.zh.code,lossCopyWritingsZh);
        copyWritingsMap.put(COPYWRITING_KEY_LOSS + RateAndLocalManager.LocalKind.en.code,lossCopyWritingsEn);
        copyWritingsMap.put(COPYWRITING_KEY_JUST + RateAndLocalManager.LocalKind.zh.code,justCopyWritingsZh);
        copyWritingsMap.put(COPYWRITING_KEY_JUST + RateAndLocalManager.LocalKind.en.code,justCopyWritingsEn);
    }

    private void loadShareProfitViews(FuturesPositionOrder holdOrderBean) {
        shareViews.clear();

        for (int i = 0; i < 2; i++) {
            LayoutInflater layoutInflater = LayoutInflater.from(this);
            View shareItemLayout = layoutInflater.inflate(R.layout.item_contract_share_profit_layout, null);
            if (i==0){
                shareView = shareItemLayout;
            }
            ViewFinder viewFinderShareItem = new ViewFinder(shareItemLayout);
            ShareConfigBean shareConfig = ShareConfigUtils.getShareConfig();
            setShareConfig(shareConfig);
            viewFinderShareItem.textView(R.id.share_title).setText(getString(i%2==0 ? R.string.string_profit_rate:R.string.string_profit_amount));
            if (holdOrderBean != null) {
                String futuresPriceUnit = KlineUtils.getFuturesPriceUnit(holdOrderBean.getSymbolId());
                String orderSide = KlineUtils.getFuturesOrderPositionTxtByIsLong(this, holdOrderBean.getIsLong());

                int color;
                String unrealisedPnl = holdOrderBean.getUnrealisedPnl();
                String randomCopyWriting = getCopyWritings(unrealisedPnl);
                viewFinderShareItem.textView(R.id.share_emoji_description).setText(randomCopyWriting);
                //当前持仓
                if (!TextUtils.isEmpty(unrealisedPnl) && unrealisedPnl.startsWith("-")) {
                    viewFinderShareItem.imageView(R.id.share_emoji).setImageResource(R.mipmap.profit_fall);
                    color = getResources().getColor(R.color.red);
                } else {
                    viewFinderShareItem.imageView(R.id.share_emoji).setImageResource(R.mipmap.profit_rise);
                    color = getResources().getColor(R.color.green);
                }
                String profitRate = holdOrderBean.getProfitRate();
                if (!TextUtils.isEmpty(profitRate)) {
                    profitRate = NumberUtils.roundFormat(NumberUtils.mul(profitRate, "100"), 2) + "%";
                }
                viewFinderShareItem.textView(R.id.profit).setText(i%2==0 ? profitRate : unrealisedPnl);
                viewFinderShareItem.textView(R.id.profit).setTextColor(color);
                viewFinderShareItem.textView(R.id.unit).setText(i%2==0 ? "" : holdOrderBean.getUnit());
                viewFinderShareItem.textView(R.id.unit).setTextColor(color);
                viewFinderShareItem.textView(R.id.token_trade_type).setText(orderSide);
                viewFinderShareItem.textView(R.id.token_trade_type).setBackgroundResource(holdOrderBean.getIsLong().equalsIgnoreCase("1")?R.drawable.bg_corner_green:R.drawable.bg_corner_red);
                //杠杆
                viewFinderShareItem.textView(R.id.token_rise_or_fall).setText(holdOrderBean.getLeverage()+"X");
                viewFinderShareItem.textView(R.id.token_rise_or_fall).setBackgroundResource(R.drawable.bg_corner_green);

                viewFinderShareItem.textView(R.id.price_title1).setText(getString(R.string.string_trade_target_name));
                viewFinderShareItem.textView(R.id.price1).setText(holdOrderBean.getSymbolName());
                viewFinderShareItem.textView(R.id.price_title2).setText(getString(R.string.string_exercise_point));
                viewFinderShareItem.textView(R.id.price2).setText(holdOrderBean.getIndices()+" " + futuresPriceUnit);
                viewFinderShareItem.textView(R.id.price_title3).setText(getString(R.string.string_option_hold_price).replace(":",""));
                viewFinderShareItem.textView(R.id.price3).setText(holdOrderBean.getAvgPrice()+" " + futuresPriceUnit);
            }
            shareViews.add(shareItemLayout);
        }
        viewPager.setOffscreenPageLimit(3);
        viewPager.setPageMargin(PixelUtils.dp2px(16));
        viewPager.setClipChildren(false);
        if (shareProfitVPAdater == null) {
            shareProfitVPAdater = new ShareVPAdater(shareViews);
            viewPager.setAdapter(shareProfitVPAdater);
        }else{
            shareProfitVPAdater.setData(shareViews);
        }
        viewPager.setPageTransformer(true,new ScalePageTransformer());

    }

    @Override
    protected void addEvent() {
        super.addEvent();
        viewFinder.find(R.id.cancel).setOnClickListener(this);
        viewFinder.find(R.id.shareWx).setOnClickListener(this);
        viewFinder.find(R.id.shareWxFriends).setOnClickListener(this);
        viewFinder.find(R.id.shareSaveImg).setOnClickListener(this);
        viewFinder.find(R.id.btnMore).setOnClickListener(this);
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {

            }

            @Override
            public void onPageSelected(int i) {
                List<View> dataList = shareProfitVPAdater.getDataList();
                if (dataList != null) {
                    shareView = dataList.get(i);
                }
            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });

    }

    @Override
    public void showShareInfo(InviteResponse response) {
        if (response != null) {
            shareUrl = response.getShareUrl();
            if (!TextUtils.isEmpty(shareUrl)) {
                if (currentShareConfig != null) {
                    setShareConfig(currentShareConfig);
                }
            }
        }
    }

    @Override
    public void setShareConfig(ShareConfigBean shareConfig) {
        currentShareConfig = shareConfig;

        for (View view : shareViews) {
            ViewFinder viewFinderShareItem = new ViewFinder(view);
            ImageView shareLogoImg = viewFinderShareItem.imageView(R.id.logo);
            TextView shareName = viewFinderShareItem.textView(R.id.name);
            TextView shareDesp = viewFinderShareItem.textView(R.id.desp);

            if(shareConfig!=null&&!TextUtils.isEmpty(shareConfig.getOpenUrl())) {
                shareName.setText(shareConfig.getTitle());
                shareDesp.setText(shareConfig.getDescription());
                String logoUrl = shareConfig.getLogoUrl();
                String openUrl = shareConfig.getOpenUrl();
                ImageView shareQrcodeImg = viewFinderShareItem.imageView(R.id.qrcode);
                CImageLoader.getInstance().load(shareLogoImg,logoUrl);
                //此处调整为 邀请地址不为空 用邀请地址，为空则用后端shareConfig配置地址
                if (!TextUtils.isEmpty(shareUrl)) {
                    openUrl = shareUrl;
                }
                if (!TextUtils.isEmpty(openUrl)) {
                    viewFinderShareItem.find(R.id.qrcode_area).setVisibility(View.VISIBLE);
                    Bitmap bitmapQR = QRCodeEncoder.syncEncodeQRCode(
                            openUrl,
                            PixelUtils.dp2px(50),
                            SkinColorUtil.getDefaultDark(this),
                            SkinColorUtil.getDefaultWhite(this),
                            BitmapUtils.getBitmapByres(ContractShareProfitActivity.this, R.mipmap.ic_launcher));
                    shareQrcodeImg.setImageBitmap(bitmapQR);
                }
            }else{
                viewFinderShareItem.find(R.id.qrcode_area).setVisibility(View.GONE);
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    /**
     * 自己：截屏分享
     * @return
     */
    private Bitmap getShareScreenBitmap() {
        String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE};
        if (!EasyPermissions.hasPermissions(this, perms)) {
            EasyPermissions.requestPermissions(this, getString(R.string.file_read_write_permission_hint), WRITE_EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE, perms);
        }else{
//            Bitmap bitmap = ShotScreenUtils.shotScreen(ShareProfitActivity.this);
//            return BitmapUtils.createBitmap(shareView,PixelUtils.getScreenWidth(),PixelUtils.getScreenHeight());
            return BitmapUtils.createBitmap3(shareView,0,0,PixelUtils.getScreenWidth(),PixelUtils.getScreenHeight());
        }

        return null;
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.cancel:
                finish();
                break;
            case R.id.btnMore:
                Bitmap shareMoreBitmap = getShareScreenBitmap();
                if (shareMoreBitmap != null) {
                    String resultPath = BitmapUtils.saveBitmap(this,shareMoreBitmap);
                    SystemShareUtils.shareImage(this,resultPath);
                }
                finish();
                break;
            case R.id.shareWx:
                Bitmap shareScreenBitmap = getShareScreenBitmap();
                ShareUtils.share(SHARE_MEDIA.WEIXIN, shareScreenBitmap);
                finish();
                break;
            case R.id.shareWxFriends:
                Bitmap shareScreenBitmap1 = getShareScreenBitmap();
                ShareUtils.share(SHARE_MEDIA.WEIXIN_CIRCLE, shareScreenBitmap1);
                finish();
                break;
            case R.id.shareSaveImg:
                Bitmap shareScreenBitmap2 = getShareScreenBitmap();
                ImageUtils.saveImageToGallery(ContractShareProfitActivity.this, shareScreenBitmap2);

//                String path = BitmapUtils.saveBitmap(resultBitmap);
//                ShotScreenUtils.AlbumScan(ShareProfitActivity.this,resultPath);
                ToastUtils.showShort(getString(R.string.string_save_success));
                finish();
                break;
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        DialogUtils.showDialogOneBtn(this, getString(R.string.string_reminder), getString(R.string.file_read_write_permission_hint), getString(R.string.string_i_know), false, new DialogUtils.OnButtonEventListener() {
            @Override
            public void onConfirm() {
                ToastUtils.showShort(getString(R.string.string_share_failed));
                finish();
            }

            @Override
            public void onCancel() {
                ToastUtils.showShort(getString(R.string.string_share_failed));
                finish();
            }
        });
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        if (requestCode == WRITE_EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE) {
            //TODO 权限请求成功
        } else {
            Toast.makeText(this, "request permission fail!", Toast.LENGTH_SHORT).show();
            finish();
        }
    }

}
